package com.atguigu.flink.timer;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.TimerService;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2023/2/28
 *
 *
 *
 *  思路:
 *          保存三个变量:
 *              ①标记，代表当前是否已经有一个定时器了。
 *                      要保证时钟只有一个定时器在工作。
 *
 *              ②保存上一个传感器的水位
 *
 *              ③定时器触发的时间
 *
 *        注意：练习时，尽量使用一种key。否则会出错!
 *
 *
 *
 */
public class Demo3_TimerExec
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
            //水印会推迟3s
            .<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner((e, ts) -> e.getTs());

        //加快水印推进
        env.setParallelism(1);

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .assignTimestampsAndWatermarks(watermarkStrategy)
                   .keyBy(WaterSensor::getId)
                   .process(new KeyedProcessFunction<String, WaterSensor, String>()
                   {

                       @Override
                       public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {

                                out.collect(ctx.getCurrentKey() +"  5s内水位连续上升....报警时间:"+timestamp);
                                //标记重置
                                ifNeedToMake=true;

                       }

                       //标记，代表当前是否已经有一个定时器了。
                       private boolean ifNeedToMake = true;
                       //定时器触发的时间
                       private long time = 0;
                       //保存上一个传感器的水位
                       private int lastVc = 0;

                       @Override
                       public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                           TimerService timerService = ctx.timerService();

                           //第一个传感器来，需要判断当前是否有定时器，没有就制定。
                           if (ifNeedToMake){

                               time = ctx.timestamp() + 5000;
                               timerService.registerEventTimeTimer(time);
                               System.out.println(value + "到达，制定定时器:"+time);
                               //当前已经有定时器了，下一个传感器来无需制定
                               ifNeedToMake = false;

                           }else {
                               //和上个传感器的水位进行比对，看是否下降，如果下降，就取消定时器
                               if (value.getVc() < lastVc){

                                   timerService.deleteEventTimeTimer(time);
                                   System.out.println(value + "到达，删除定时器:"+time);
                                   ifNeedToMake = true;

                               }
                           }

                           //保留当前的水位，方便下一个传感器使用
                           lastVc = value.getVc();

                       }
                   })
                   .print();


                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }

}
